#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
import datetime, os, re, requests, sys, imghdr
requests.packages.urllib3.disable_warnings()

# 设置post上传接口
urls = "https://www.ladydaily.com/tools/upload/"


def upload_img():
    # 设置for 循环，防止一次性 导入 多张img 先判断有多少张图片
    for i in range(1, len(sys.argv)):
        # 先判断是否是文件会更快一点
        if os.path.isfile(sys.argv[i]):  # 判断文件是否存在，不存在则为链接
            new_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + "." + imghdr.what(sys.argv[i])  # 时间戳重命名
            imageFileContent = open(sys.argv[i], 'rb')
        elif "http://" or "https://" in sys.argv[i]:  # 目前不支持 ftp
            # 这里用try 是因为re.match如果匹配不到img_type 就会报错 AttributeError: 'NoneType' object has no attribute 'group'
            try:
                imageFileContent = requests.get(sys.argv[i], timeout=5, verify=False).content # 缓存文件
            except requests.exceptions.ConnectTimeout:
                print("网络异常")
                exit()
            except:
                try:
                    new_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + "." + re.match(r"^[\s\S]*\.(jpg|png|webp|jpeg|gif)", sys.argv[i]).group(1) # 生成文件名
                except:
                    try:
                        new_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + "." + imghdr.what(None, requests.get(sys.argv[1], timeout=5, verify=False).content) # 生成文件名
                    except requests.exceptions.ConnectTimeout:
                        print("网络异常")
                        exit()
                    except:
                        print("发生了什么？")
                        exit()
        else:
            print("发生了什么？")
            exit()
        try:
            upload_result = requests.post(urls, files={'file': (new_name, imageFileContent)}, timeout=5, verify=False)
            if upload_result.json()["success"]:
                print(upload_result.json()["data"]["o_url"])
                # os.remove(sys.argv[i])
            else:
                print('Error: ' + upload_result.json())
        except requests.exceptions.ConnectTimeout:
            print("网络异常")
            exit()
        except:
            print('Error: ' + upload_result.json())


# 覆盖图片不支持 URL图片，只允许本地图片，尽量不要有空格 比如 C:\User\xiao ge ge\WeChat file 这种百分百报错
def cover_img():
    for i in range(1, len(sys.argv)):
        new_name = os.path.basename(sys.argv[i])
        if os.path.isfile(sys.argv[i]):
            imageFileContent = open(sys.argv[i], 'rb')
        elif "http://" or "https://" in sys.argv[i]:
            try:
                imageFileContent = requests.get(sys.argv[i], timeout=5, verify=False).content
            except requests.exceptions.ConnectTimeout:
                print("网络异常")
                exit()
        try:
            upload_result = requests.post(urls, files={'file': (new_name, imageFileContent)}, timeout=5, verify=False)
            if upload_result.json()["success"]:
                print(upload_result.json()["data"]["o_url"])
            else:
                print('Error: ' + upload_result.json())
        except requests.exceptions.ConnectTimeout:
            print("网络异常")
            exit()
        except:
            print('Error: ' + upload_result.json())


if __name__ == '__main__':
    upload_img()
    # TODO 这里是覆盖图片的地方，如果需要则注释上面那行
    # cover_img()
    # exit()